<template>
	 
	 
	 
	 <el-button type="primary" v-on:click="showDialog">新增</el-button>
	 
	 <el-table :data="userPageInfo.list">
		 <el-table-column prop="username" label="用户名"></el-table-column>
		 <el-table-column prop="email" label="邮箱"></el-table-column>
		 <el-table-column prop="mobile" label="手机号"></el-table-column>
		 <el-table-column prop="create_time" label="创建时间"></el-table-column>
		 
		   <el-table-column  label="状态">
			   
			   <template #default="scope">
				   <span v-if="scope.row.status==0">
					   <el-button type="danger">禁用</el-button>
				   </span>
				   <span v-else>
					   <el-button type="success">正常</el-button>
				   </span>
				   
			   </template>
		   </el-table-column>
		   
		   
	
		<el-table-column  label="操作">
				   <template #default="scope">
					   <el-button type="primary">修改</el-button>
					   <el-button type="danger" v-on:click="deleteUser(scope.row.user_id)">删除</el-button>
				   </template>
		</el-table-column>
		
	 </el-table>
	 <el-pagination
	       v-model:current-page="userPageInfo.pageNum"
	       v-model:page-size="userPageInfo.pageSize"
	       :page-sizes="[5,10,15,20,100]"
	        size="default"
	       layout="total, sizes, prev, pager, next, jumper"
	       :total="userPageInfo.total"
	       @size-change="handleSizeChange"
	       @current-change="handleCurrentChange"
	     />
	
	

	<el-dialog
	    v-model="dialogVisible"
	    :title="dialogTitle"
	    width="600"
	  >
	   
	   {{sysUserInfo}}
	    <el-form
	       ref="ruleFormRef"
	       style="max-width: 600px"
	       :model="sysUserInfo"
	       :rules="dialogFormRules"
	       label-width="100"
	     >
	       <el-form-item label="用户名" prop="username">
	         <el-input v-model="sysUserInfo.username" />
	       </el-form-item>
		   <el-form-item label="密码" prop="password">
		     <el-input type="password" v-model="sysUserInfo.password" />
		   </el-form-item>
		   <el-form-item label="确认密码" prop="confirmPassword">
		     <el-input type="password" v-model="sysUserInfo.confirmPassword" />
		   </el-form-item>
		   <el-form-item label="邮箱" prop="email">
		     <el-input v-model="sysUserInfo.email" />
		   </el-form-item>
		   <el-form-item label="手机号" prop="mobile">
		     <el-input v-model="sysUserInfo.mobile" />
		   </el-form-item>
		   <el-form-item label="角色" prop="mobile">
		     <el-checkbox-group v-model="sysUserInfo.selectedRoleId">
		         <el-checkbox v-for="(item,index) in sysRoleInfo" 
					:label="item.role_name"  :value="item.role_id"  :key="item.role_id" />
		     </el-checkbox-group>  
		   </el-form-item>
		   <el-form-item label="状态" prop="name">
			  <el-radio-group v-model="sysUserInfo.status">
				 <el-radio :value="0">禁用</el-radio>
				 <el-radio :value="1">正常</el-radio>
			   </el-radio-group>
		   </el-form-item>
	   </el-form>
	   
	
	   
	   
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="dialogVisible = false">Cancel</el-button>
	        <el-button type="primary" @click="saveSysUser">
	          保存
	        </el-button>
	      </div>
	    </template>
	</el-dialog>
	
	
</template>

<script setup>
	import {ref,onMounted,getCurrentInstance} from 'vue';
	import {ElMessage} from 'element-plus';
	
	let {proxy} = getCurrentInstance();
	
	
	let userPageInfo = ref({});
	let sysRoleInfo = ref([]); //后端返回的所有角色信息
	
	let handleSizeChange = (pageSize)=>{
		console.log("handleSizeChange",pageSize)
		queryWhere.value.pageSize = pageSize;
		initData();
	}
	
	
	let handleCurrentChange = (pageNum)=>{
		console.log("handleCurrentChange",pageNum)
		queryWhere.value.pageNum = pageNum;
		initData();
	}
	
	let queryWhere = ref({
		pageNum:1,
		pageSize:5,
		userName:null,
		
	})
	
	
	let initData=()=>{
		proxy.$axios.get("/sysUserController/queryData",{params:queryWhere.value})
		.then((serverData)=>{
			console.log("服务端返回的数据为:",serverData.data.data)
			if (serverData.data.code==0){
				userPageInfo.value = serverData.data.data
			}else{
				ElMessage({type:"error",message:serverData.data.msg})
			}
			
		})
		
	}
	
	let initRoleData=()=>{ //获得所有的角色信息
		proxy.$axios.get("/sysRoleController/queryData")
		.then((serverData)=>{
			
			if (serverData.data.code==0){
				sysRoleInfo.value = serverData.data.data
			}else{
				ElMessage({type:"error",message:serverData.data.msg})
			}
			
		})
	}
	
	
	onMounted(()=>{
		initData();
		// 查询角色表中的所有记录
		initRoleData();
	})
	
	
	/**新增操作相关的变量和函数*/
	let dialogTitle = ref("新增")
	let dialogVisible = ref(false)
	let sysUserInfo = ref({//该对象是提交给后端的与表单做双向绑定的对象
		"user_id": null,
		"username": "",
		"confirmPassword":"",
		"password": "",
		"email": "",
		"mobile": "",
		"status": 1,
		"shop_id": 1,
		 "selectedRoleId":[]// 在新增或修改界面中存储选中项(角色)的id
	})
	
	let showDialog= ()=>{
		dialogVisible.value = true;
	}
	
	
	let ruleFormRef = ref();//该变量的名称与表单组件el-from的ref属性值相同，该变量就代表表单组件
	
	
	//密码的校验规则
	const validatePass = (rule, value, callback) => {
	  if (value === '') {
	    callback(new Error('请输入密码'))
	  } else {
	    if (sysUserInfo.value.confirmPassword !== '') {
	      if (!ruleFormRef.value) return
	      ruleFormRef.value.validateField('confirmPassword')//触发确认密码的校验规则
	    }
	    callback()
	  }
	}
	const validateConfirmPass = (rule, value, callback) => {
		
	  if (value === '') {
	    callback(new Error('请输入确认密码'))
	  } else if (value !== sysUserInfo.value.password) {
	    callback(new Error("两次输入的密码不一致"))
	  } else {
	    callback()
	  }
	}
	
	
	
	//弹出界面的表单验证规则
	let dialogFormRules = ref({
		username:[
			{ required: true, message: '用户名不能为空', trigger: 'blur' },
		],
		password:[
			{ required: true, message: '密码名不能为空', trigger: 'blur' },
			{validator: validatePass ,trigger: 'blur'}
		],
		confirmPassword:[
			{ required: true, message: '确认密码不能为空', trigger: 'blur' },
			{validator: validateConfirmPass ,trigger: 'blur'}
		],
		email:[
			{ required: true, message: '邮箱不能为空', trigger: 'blur' },
		],
		mobile:[
			{ required: true, message: '手机号不能为空', trigger: 'blur' },
		]
		
	})
	
	//先验证表单，再提交表单
	let saveSysUser=()=>{
		
		ruleFormRef.value.validate((valid,fields)=>{
			if (valid){//代表验证通过
			//发请求给后端，将sysUserInfo代表表单数据传递给后端
				let url = "/sysUserController/saveUser"
				//proxy.$axios.get(url,{params:{对象名:属性名}})  注：get方法的传参部分需要添加一个params属性
			//	proxy.$axios.get(url,{params:sysUserInfo.value}) 
			//	proxy.$axios.get(url,sysUserInfo.value) 
				//但post方法不需要{params:{}},直接传递对象即要
			//	proxy.$axios.get(url,{params:sysUserInfo.value})
			if(dialogTitle.value=="新增"){
				proxy.$axios.post(url,sysUserInfo.value)   
				.then((serverData)=>{
					if (serverData.data.code==0){
						initData();
						ElMessage({type:"success",message:"添加成功"})
						dialogVisible.value = false;
					}else{
						ElMessage({type:"error",message:serverData.data.msg})
					}
					
				})
				
				
				
				/*proxy.$axios({
					method:"delete",
					url:url,
					data:sysUserInfo.value
				}).then((serverData)=>{
					
				})*/
			}else{
				proxy.$axios.put(url,sysUserInfo.value)
				.then((serverData)=>{
					if (serverData.data.code==0){
						initData();
						ElMessage({type:"success",message:"修改成功"})
						dialogVisible.value = false;
					}else{
						ElMessage({type:"error",message:serverData.data.msg})
					}
					
				})
			}
				
				
			}
		})
		
	}
	
	
	/*删除用户信息的代码*/
	let deleteUser = (userId)=>{
		let url = `/sysUserController/deleteUser/${userId}`;
		proxy.$axios.delete(url)
		.then((serverData)=>{
			if (serverData.data.code==0){
				initData();
				ElMessage({type:"success",message:"删除成功"})
				dialogVisible.value = false;
			}else{
				ElMessage({type:"error",message:serverData.data.msg})
			}
			
		})
	}
	
	
	
	//1 点击页面的新增或修改按钮，需要先将所有的角色信息查询出来，以复选框的形式显示的界面中
	   //(以上步骤也可以在页面加载时就查询出来)
	//2  如果点击的是修改按钮，则需要将当前管理的编号传递给后端，获取该管理员对应的角色信息
	    //（ 目的:根据管理员所属的角色选中界面中相应的复选框）
	//3 点击保存按钮，除了将管理员的信息传递给后端外，还要将复选框选中的角色编号传递给后端	
	
	
</script>

<style>
</style>